package my.myorm.tool.jdbc;

/**
 * 事务上下文，负责事务的生命周期
 *
 * @author Skeven Huang
 * @version 1.0
 */
public class TransactionContext {
    private static ThreadLocal<MyTransaction> transactions = new ThreadLocal<MyTransaction>();

    /**
     * 获取当前事务中的SQLExecutor
     *
     * @return
     * @throws Exception
     */
    public static SQLExecutor getSQLExecutorInCurrentTransaction() throws Exception {
        MyTransaction transaction = transactions.get();
        if (transaction == null || transaction.getStatus() != 1) {
            return null;
        }
        return transaction.getExecutor();
    }

    /**
     * 开始事务
     *
     * @throws Exception
     */
    public static void beginTransaction() throws Exception {
        MyTransaction transaction = transactions.get();
        if (transaction == null) {
            MyTransaction tran = new MyTransaction();
            tran.setStatus(1);
            tran.setExecutor(new SQLExecutor(true));
            transactions.set(tran);
        } else {
            if (transaction.getStatus() != 4) {
                throw new Exception("last transaction is not over");
            } else {
                transaction.setExecutor(new SQLExecutor(true));
                transaction.setStatus(1);
            }
        }
    }

    /**
     * 提交事务
     *
     * @throws Exception
     */
    public static void commitTransaction() throws Exception {
        MyTransaction transaction = transactions.get();
        if (transaction == null) {
            throw new Exception("no transaction to commit");
        }
        if (transaction.getStatus() != 1) {
            throw new Exception("invalid transaction status");
        }
        transaction.getExecutor().commit();
        transaction.setStatus(2);
    }

    /**
     * 回滚事务
     *
     * @throws Exception
     */
    public static void rollbackTransaction() throws Exception {
        MyTransaction transaction = transactions.get();
        if (transaction == null) {
            throw new Exception("no transaction to rollback");
        }
        if (transaction.getStatus() != 1) {
            throw new Exception("invalid transaction status");
        }
        transaction.getExecutor().rollBack();
        transaction.setStatus(3);
    }

    /**
     * 结束事务，注意：若启用了事务，必须保证改函数的执行，否则数据库链接不会关闭
     *
     * @throws Exception
     */
    public static void endTransaction() throws Exception {
        MyTransaction transaction = transactions.get();
        if (transaction == null) {
            throw new Exception("no transaction to rollback");
        }
        transaction.getExecutor().close();
        transaction.setStatus(4);
    }
}
